﻿using System;
using System.Data.Linq;
using System.Linq;
using System.Reflection;
using log4net;

namespace TruyenTranhCrawler.Data
{
    [Serializable]
    public class BaseObject
    {
        public static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        public const int PageSizeDefault = 16;
        public const int PageSize50 = 50;
        public virtual void Save()
        {
            try
            {
                using (var context = new CmsDataContext())
                {
                    context.GetTable(GetType()).InsertOnSubmit(this);
                    context.SubmitChanges();
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }
        public virtual void Update()
        {
            try
            {
                using (var context = new CmsDataContext())
                {
                    context.GetTable(GetType()).Attach(this);
                    context.Refresh(RefreshMode.KeepCurrentValues, this);
                    context.SubmitChanges();
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }
        public virtual void Delete()
        {
            try
            {
                using (var context = new CmsDataContext())
                {
                    context.GetTable(GetType()).Attach(this);
                    context.GetTable(GetType()).DeleteOnSubmit(this);
                    context.SubmitChanges();
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }

        public static int[] ToIntArray(string ids)
        {
            if (string.IsNullOrEmpty(ids)) return new int[0];
            return ids.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(n => Convert.ToInt32(n)).ToArray();
        }
        public static long[] ToBigIntArray(string ids)
        {
            if (string.IsNullOrEmpty(ids)) return new long[0];
            return ids.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(n => Convert.ToInt64(n)).ToArray();
        }

        public static string GetSafeName(string name)
        {
            return Utils.Process.ConvertToSafeMarks(name).Trim().ToLower();
        }
        public static string GetSortName(string name)
        {
            return Utils.Process.ConvertToSafeMarks(name).Replace("-", "").Trim().ToLower();
        }
        public static string GetSortNameFromSafeName(string safeName)
        {
            return safeName.Replace("-", "").Trim().ToLower();
        }
    }
}
